home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1994 August: Tool Chest / Dev.CD Aug 94.toast / Tool Chest / Development Platforms / Macintosh Common Lisp Related / Tutorials / lisp-tutorial.text < prev    next >
Encoding:
Text File  |  1993-02-26  |  29.6 KB  |  1,129 lines  |  [TEXT/ttxt]

  1.               Common LISP Hints
  2.               Geoffrey J. Gordon
  3.              <ggordon@cs.cmu.edu>
  4.                Friday, February 5, 1993
  5.  
  6. Note: This tutorial introduction to Common Lisp was written for the
  7. CMU environment, so some of the details of running lisp toward the end
  8. may differ from site to site.
  9.  
  10. Further Information
  11.  
  12. The best LISP textbook I know of is
  13.  
  14.   Guy L. Steele Jr. _Common LISP: the Language_. Digital Press. 1984.
  15.  
  16. The first edition is easier to read; the second describes a more recent
  17. standard. (The differences between the two standards shouldn't affect
  18. casual programmers.)
  19.  
  20. A book by Dave Touretsky has also been recommended to me, although I
  21. haven't read it, so I can't say anything about it.
  22.  
  23. Some LISPS have online manuals. See "Getting Started" at the end of
  24. this document.
  25.  
  26.  
  27.  
  28. Symbols
  29.  
  30. A symbol is just a string of characters. There are restrictions on what
  31. you can include in a symbol and what the first character can be, but as
  32. long as you stick to letters, digits, and hyphens, you'll be safe.
  33. (Except that if you use only digits and possibly an initial hyphen,
  34. LISP will think you typed an integer rather than a symbol.) Some
  35. examples of symbols:
  36.  
  37.     a
  38.     b
  39.     c1
  40.     foo
  41.     bar
  42.     baaz-quux-garply
  43.  
  44. Some things you can do with symbols follow. (Things after a ">" prompt
  45. are what you type to the LISP interpreter, while other things are what
  46. the LISP interpreter prints back to you. The ";" is LISP's comment
  47. character: everything from a ";" to the next carriage return is
  48. ignored.)
  49.  
  50. > (setq a 5)        ;store a number as the value of a symbol
  51. 5
  52. > a            ;take the value of a symbol
  53. 5
  54. > (let ((a 6)) a)    ;bind the value of a symbol temporarily to 6
  55. 6
  56. > a            ;the value returns to 5 once the let is finished
  57. 5
  58. > (+ a 6)        ;use the value of a symbol as an argument to a function
  59. 11
  60. > b            ;try to take the value of a symbol which has no value
  61. Error: Attempt to take the value of the unbound symbol B
  62.  
  63. There are two special symbols, t and nil. The value of t is defined
  64. always to be t, and the value of nil is defined always to be nil. LISP
  65. uses t and nil to represent true and false. An example of this use is
  66. in the if statement, described more fully later:
  67.  
  68. > (if t 5 6)
  69. 5
  70. > (if nil 5 6)
  71. 6
  72. > (if 4 5 6)
  73. 5
  74.  
  75. The last example is odd but correct: nil means false, and anything else
  76. means true. (Unless we have a reason to do otherwise, we use t to mean
  77. true, just for the sake of clarity.)
  78.  
  79. Symbols like t and nil are called self-evaluating symbols, because
  80. they evaluate to themselves. There is a whole class of self-evaluating
  81. symbols called keywords; any symbol whose name starts with a colon is a
  82. keyword. (See below for some uses for keywords.) Some examples:
  83.  
  84. > :this-is-a-keyword
  85. :THIS-IS-A-KEYWORD
  86. > :so-is-this
  87. :SO-IS-THIS
  88. > :me-too
  89. :ME-TOO
  90.  
  91.  
  92.  
  93. Numbers
  94.  
  95. An integer is a string of digits optionally preceded by + or -. A real
  96. number looks like an integer, except that it has a decimal point and
  97. optionally can be written in scientific notation. A rational looks like
  98. two integers with a / between them. LISP supports complex numbers,
  99. which are written #c(r i) (where r is the real part and i is the
  100. imaginary part). A number is any of the above. Here are some numbers:
  101.  
  102.     5
  103.     17
  104.     -34
  105.     +6
  106.     3.1415
  107.     1.722e-15
  108.     #c(1.722e-15 0.75)
  109.  
  110. The standard arithmetic functions are all available: +, -, *, /, floor,
  111. ceiling, mod, sin, cos, tan, sqrt, exp, expt, and so forth. All of them
  112. accept any kind of number as an argument. +, -, *, and / return a
  113. number according to type contagion: an integer plus a rational is a
  114. rational, a rational plus a real is a real, and a real plus a complex
  115. is a complex. Here are some examples:
  116.  
  117. > (+ 3 3/4)        ;type contagion
  118. 15/4 
  119. > (exp 1)        ;e
  120. 2.7182817 
  121. > (exp 3)        ;e*e*e
  122. 20.085537 
  123. > (expt 3 4.2)        ;exponent with a base other than e
  124. 100.90418
  125. > (+ 5 6 7 (* 8 9 10))    ;the fns +-*/ all accept multiple arguments
  126.  
  127. There is no limit to the absolute value of an integer except the memory
  128. size of your computer. Be warned that computations with bignums (as
  129. large integers are called) can be *slow*. (So can computations with
  130. rationals, especially compared to the corresponding computations with
  131. small integers or floats.)
  132.  
  133.  
  134.  
  135. Conses
  136.  
  137. A cons is just a two-field record. The fields are called "car" and
  138. "cdr", for historical reasons. (On the first machine where LISP was
  139. implemented, there were two instructions CAR and CDR which stood for
  140. "contents of address register" and "contents of decrement register".
  141. Conses were implemented using these two registers.)
  142.  
  143. Conses are easy to use:
  144.  
  145. > (cons 4 5)        ;Allocate a cons. Set the car to 4 and the cdr to 5.
  146. (4 . 5)
  147. > (cons (cons 4 5) 6)
  148. ((4 . 5) . 6)
  149. > (car (cons 4 5))
  150. 4
  151. > (cdr (cons 4 5))
  152. 5
  153.  
  154.  
  155.  
  156. Lists
  157.  
  158. You can build many structures out of conses. Perhaps the simplest is a
  159. linked list: the car of each cons points to one of the elements of the
  160. list, and the cdr points either to another cons or to nil. You can
  161. create such a linked list with the list fuction:
  162.  
  163. > (list 4 5 6)
  164. (4 5 6)
  165.  
  166. Notice that LISP prints linked lists a special way: it omits some of
  167. the periods and parentheses. The rule is: if the cdr of a cons is nil,
  168. LISP doesn't bother to print the period or the nil; and if the cdr of
  169. cons A is cons B, then LISP doesn't bother to print the period for cons
  170. A or the parentheses for cons B. So:
  171.  
  172. > (cons 4 nil)
  173. (4)
  174. > (cons 4 (cons 5 6))
  175. (4 5 . 6)
  176. > (cons 4 (cons 5 (cons 6 nil)))
  177. (4 5 6)
  178.  
  179. The last example is exactly equivalent to the call (list 4 5 6). Note
  180. that nil now means the list with no elements: the cdr of (a b), a list
  181. with 2 elements, is (b), a list with 1 element; and the cdr of (b), a
  182. list with 1 element, is nil, which therefore must be a list with no
  183. elements.
  184.  
  185. The car and cdr of nil are defined to be nil.
  186.  
  187. If you store your list in a variable, you can make it act like a stack:
  188.  
  189. > (setq a nil)
  190. NIL
  191. > (push 4 a)
  192. (4)
  193. > (push 5 a)
  194. (5 4)
  195. > (pop a)
  196. 5
  197. > a
  198. (4)
  199. > (pop a)
  200. 4
  201. > (pop a)
  202. NIL
  203. > a
  204. NIL
  205.  
  206.  
  207.  
  208. Functions
  209.  
  210. You saw one example of a function above. Here are some more:
  211.  
  212. > (+ 3 4 5 6)            ;this function takes any number of arguments
  213. 18
  214. > (+ (+ 3 4) (+ (+ 4 5) 6))    ;isn't prefix notation fun?
  215. 22
  216. > (defun foo (x y) (+ x y 5))    ;defining a function
  217. FOO
  218. > (foo 5 0)            ;calling a function
  219. 10
  220. > (defun fact (x)        ;a recursive function
  221.     (if (> x 0) 
  222.       (* x (fact (- x 1)))
  223.       1))
  224. FACT
  225. > (fact 5)
  226. 120
  227. > (defun a (x) (if (= x 0) t (b (- x))))    ;mutually recursive functions
  228. A
  229. > (defun b (x) (if (> x 0) (a (- x 1)) (a (+ x 1))))
  230. B
  231. > (a 5)
  232. T
  233. > (defun bar (x)        ;a function with multiple statements in
  234.     (setq x (* x 3))        ;its body -- it will return the value
  235.     (setq x (/ x 2))        ;returned by its final statement
  236.     (+ x 4))
  237. BAR
  238. > (bar 6)
  239. 13
  240.  
  241. When we defined foo, we gave it two arguments, x and y. Now when we
  242. call foo, we are required to provide exactly two arguments: the first
  243. will become the value of x for the duration of the call to foo, and the
  244. second will become the value of y for the duration of the call. In
  245. LISP, most variables are lexically scoped; that is, if foo calls bar
  246. and bar tries to reference x, bar will not get foo's value for x.
  247.  
  248. The process of assigning a symbol a value for the duration of some
  249. lexical scope is called binding.
  250.  
  251. You can specify optional arguments for your functions. Any argument
  252. after the symbol &optional is optional:
  253.  
  254. > (defun bar (x &optional y) (if y x 0))
  255. BAR
  256. > (defun baaz (&optional (x 3) (z 10)) (+ x z))
  257. BAAZ
  258. > (bar 5)
  259. 0
  260. > (bar 5 t)
  261. 5
  262. > (baaz 5)
  263. 15
  264. > (baaz 5 6)
  265. 11
  266. > (baaz)
  267. 13
  268.  
  269. It is legal to call the function bar with either one or two arguments.
  270. If it is called with one argument, x will be bound to the value of that
  271. argument and y will be bound to nil; if it is called with two
  272. arguments, x and y will be bound to the values of the first and second
  273. argument, respectively.
  274.  
  275. The function baaz has two optional arguments. It specifies a default
  276. value for each of them: if the caller specifies only one argument, z
  277. will be bound to 10 instead of to nil, and if the caller specifies no
  278. arguments, x will be bound to 3 and z to 10.
  279.  
  280. You can make your function accept any number of arguments by ending its
  281. argument list with an &rest parameter. LISP will collect all arguments
  282. not otherwise accounted for into a list and bind the &rest parameter to
  283. that list. So:
  284.  
  285. > (defun foo (x &rest y) y)
  286. FOO
  287. > (foo 3)
  288. NIL
  289. > (foo 4 5 6)
  290. (5 6)
  291.  
  292. Finally, you can give your function another kind of optional argument
  293. called a keyword argument. The caller can give these arguments in any
  294. order, because they're labelled with keywords.
  295.  
  296. > (defun foo (&key x y) (cons x y))
  297. FOO
  298. > (foo :x 5 :y 3)
  299. (5 . 3)
  300. > (foo :y 3 :x 5)
  301. (5 . 3)
  302. > (foo :y 3)
  303. (NIL . 3)
  304. > (foo)
  305. (NIL)
  306.  
  307. An &key parameter can have a default value too:
  308.  
  309. > (defun foo (&key (x 5)) x)
  310. FOO
  311. > (foo :x 7)
  312. 7
  313. > (foo)
  314. 5
  315.  
  316.  
  317.  
  318. Printing
  319.  
  320. Some functions can cause output. The simplest one is print, which
  321. prints its argument and then returns it.
  322.  
  323. > (print 3)
  324. 3
  325. 3
  326.  
  327. The first 3 above was printed, the second was returned.
  328.  
  329. If you want more complicated output, you will need to use format.
  330. Here's an example:
  331.  
  332. > (format t "An atom: ~S~%and a list: ~S~%and an integer: ~D~%"
  333.           nil (list 5) 6)
  334. An atom: NIL
  335. and a list: (5)
  336. and an integer: 6
  337.  
  338. The first argument to format is either t, nil, or a stream. T specifies
  339. output to the terminal. Nil means not to print anything but to return a
  340. string containing the output instead. Streams are general places for
  341. output to go: they can specify a file, or the terminal, or another
  342. program. This handout will not describe streams in any further detail.
  343.  
  344. The second argument is a formatting template, which is a string
  345. optionally containing formatting directives.
  346.  
  347. All remaining arguments may be referred to by the formatting
  348. directives. LISP will replace the directives with some appropriate
  349. characters based on the arguments to which they refer and then print
  350. the resulting string.
  351.  
  352. Format always returns nil unless its first argument is nil, in which
  353. case it prints nothing and returns a string.
  354.  
  355. There are three different directives in the above example: ~S, ~D, and
  356. ~%. The first one accepts any LISP object and is replaced by a printed
  357. representation of that object (the same representation which is
  358. produced by print). The second one accepts only integers. The third one
  359. doesn't refer to an argument; it is always replaced by a carriage
  360. return.
  361.  
  362. Another useful directive is ~~, which is replaced by a single ~.
  363.  
  364. Refer to a LISP manual for (many, many) additional formatting
  365. directives.
  366.  
  367.  
  368.  
  369. Forms and the Top-Level Loop
  370.  
  371. The things which you type to the LISP interpreter are called forms; the
  372. LISP interpreter repeatedly reads a form, evaluates it, and prints the
  373. result. This procedure is called the read-eval-print loop.
  374.  
  375. Some forms will cause errors. After an error, LISP will put you into
  376. the debugger so you can try to figure out what caused the error. LISP
  377. debuggers are all different; but most will respond to the command
  378. ":help" by giving some form of help.
  379.  
  380. In general, a form is either an atom (for example, a symbol, an
  381. integer, or a string) or a list. If the form is an atom, LISP evaluates
  382. it immediately. Symbols evaluate to their value; integers and strings
  383. evaluate to themselves. If the form is a list, LISP treats its first
  384. element as the name of a function; it evaluates the remaining elements
  385. recursively, and then calls the function with the values of the
  386. remaining elements as arguments.
  387.  
  388. For example, if LISP sees the form (+ 3 4), it treats + as the name of
  389. a function. It then evaluates 3 to get 3 and 4 to get 4; finally it
  390. calls + with 3 and 4 as the arguments. The + function returns 7, which
  391. LISP prints.
  392.  
  393. The top-level loop provides some other conveniences; one particularly
  394. convenient convenience is the ability to talk about the results of
  395. previously typed forms. LISP always saves its most recent three
  396. results; it stores them as the values of the symbols *, **, and ***.
  397. For example:
  398.  
  399. > 3
  400. 3
  401. > 4
  402. 4
  403. > 5
  404. 5
  405. > ***
  406. 3
  407. > ***
  408. 4
  409. > ***
  410. 5
  411. > **
  412. 4
  413. > *
  414. 4
  415.  
  416.  
  417.  
  418. Special forms
  419.  
  420. There are a number of special forms which look like function calls but
  421. aren't. These include control constructs such as if statements and do
  422. loops; assignments like setq, setf, push, and pop; definitions such as
  423. defun and defstruct; and binding constructs such as let. (Not all of
  424. these special forms have been mentioned yet. See below.)
  425.  
  426. One useful special form is the quote form: quote prevents its argument
  427. from being evaluated. For example:
  428.  
  429. > (setq a 3)
  430. 3
  431. > a
  432. 3
  433. > (quote a)
  434. A
  435. > 'a            ;'a is an abbreviation for (quote a)
  436. A
  437.  
  438. Another similar special form is the function form: function causes its
  439. argument to be interpreted as a function rather than being evaluated.
  440. For example:
  441.  
  442. > (setq + 3)
  443. 3
  444. > +
  445. 3
  446. > '+
  447. +
  448. > (function +)
  449. #<Function + @ #x-fbef9de>
  450. > #'+            ;#'+ is an abbreviation for (function +)
  451. #<Function + @ #x-fbef9de>
  452.  
  453. The function special form is useful when you want to pass a function as
  454. an argument to another function. See below for some examples of
  455. functions which take functions as arguments.
  456.  
  457.  
  458.  
  459. Binding
  460.  
  461. Binding is lexically scoped assignment. It happens to the variables in
  462. a function's parameter list whenever the function is called: the formal
  463. parameters are bound to the actual parameters for the duration of the
  464. function call. You can bind variables anywhere in a program with the
  465. let special form, which looks like this:
  466.  
  467.     (let ((var1 val1)
  468.           (var2 val2)
  469.           ...)
  470.       body)
  471.  
  472. Let binds var1 to val1, var2 to val2, and so forth; then it executes
  473. the statements in its body. The body of a let follows exactly the same
  474. rules that a function body does. Some examples:
  475.  
  476. > (let ((a 3)) (+ a 1))
  477. 4
  478. > (let ((a 2) 
  479.         (b 3)
  480.         (c 0))
  481.     (setq c (+ a b))
  482.     c)
  483. 5
  484. > (setq c 4)
  485. 4
  486. > (let ((c 5)) c)
  487. 5
  488. > c
  489. 4
  490.  
  491. Instead of (let ((a nil) (b nil)) ...), you can write (let (a b) ...).
  492.  
  493. The val1, val2, etc. inside a let cannot reference the variables var1,
  494. var2, etc. that the let is binding. For example,
  495.  
  496. > (let ((x 1)
  497.         (y (+ x 1)))
  498.     y)
  499. Error: Attempt to take the value of the unbound symbol X
  500.  
  501. If the symbol x already has a global value, stranger happenings will
  502. result:
  503.  
  504. > (setq x 7)
  505. 7
  506. > (let ((x 1)
  507.         (y (+ x 1)))
  508.     y)
  509. 8
  510.  
  511. The let* special form is just like let except that it allows values to
  512. reference variables defined earlier in the let*. For example,
  513.  
  514. > (setq x 7)
  515. 7
  516. > (let* ((x 1)
  517.          (y (+ x 1)))
  518.     y)
  519. 2
  520.  
  521. The form
  522.  
  523.     (let* ((x a)
  524.            (y b))
  525.       ...) 
  526.  
  527. is equivalent to
  528.  
  529.     (let ((x a))
  530.       (let ((y b))
  531.         ...))
  532.  
  533.  
  534.  
  535. Dynamic Scoping
  536.  
  537. The let and let* forms provide lexical scoping, which is what you
  538. expect if you're used to programming in C or Pascal. Dynamic scoping is
  539. what you get in BASIC: if you assign a value to a dynamically scoped
  540. variable, every mention of that variable returns that value until you
  541. assign another value to the same variable.
  542.  
  543. In LISP, dynamically scoped variables are called special variables. You
  544. can declare a special variable with the defvar special form. Here are
  545. some examples of lexically and dynamically scoped variables.
  546.  
  547. In this example, the function check-regular references a regular (ie,
  548. lexically scoped) variable. Since check-regular is lexically outside of
  549. the let which binds regular, check-regular returns the variable's
  550. global value.
  551.  
  552. > (setq regular 5)
  553. > (defun check-regular () regular)
  554. CHECK-REGULAR 
  555. > (check-regular)
  556. > (let ((regular 6)) (check-regular))
  557.  
  558. In this example, the function check-special references a special (ie,
  559. dynamically scoped) variable. Since the call to check-special is
  560. temporally inside of the let which binds special, check-special returns
  561. the variable's local value.
  562.  
  563. > (defvar *special* 5)
  564. *SPECIAL*
  565. > (defun check-special () *special*)
  566. CHECK-SPECIAL
  567. > (check-special)
  568. 5
  569. > (let ((*special* 6)) (check-special))
  570. 6
  571.  
  572. By convention, the name of a special variable begins and ends with a *.
  573. Special variables are chiefly used as global variables, since
  574. programmers usually expect lexical scoping for local variables and
  575. dynamic scoping for global variables.
  576.  
  577. For more information on the difference between lexical and dynamic
  578. scoping, see _Common LISP: the Language_.
  579.  
  580.  
  581.  
  582. Arrays
  583.  
  584. The function make-array makes an array. The aref function accesses its
  585. elements. All elements of an array are initially set to nil. For
  586. example:
  587.  
  588. > (make-array '(3 3))
  589. #2a((NIL NIL NIL) (NIL NIL NIL) (NIL NIL NIL))
  590. > (aref * 1 1)
  591. NIL
  592. > (make-array 4)    ;1D arrays don't need the extra parens
  593. #(NIL NIL NIL NIL)
  594.  
  595. Array indices always start at 0.
  596.  
  597. See below for how to set the elements of an array.
  598.  
  599.  
  600.  
  601. Strings
  602.  
  603. A string is a sequence of characters between double quotes. LISP
  604. represents a string as a variable-length array of characters. You can
  605. write a string which contains a double quote by preceding the quote
  606. with a backslash; a double backslash stands for a single backslash. For
  607. example:
  608.  
  609.     "abcd" has 4 characters
  610.     "\"" has 1 character
  611.     "\\" has 1 character
  612.  
  613. Here are some functions for dealing with strings:
  614.  
  615. > (concatenate 'string "abcd" "efg")
  616. "abcdefg"
  617. > (char "abc" 1)
  618. #\b            ;LISP writes characters preceded by #\
  619. > (aref "abc" 1)
  620. #\b            ;remember, strings are really arrays
  621.  
  622. The concatenate function can actually work with any type of sequence:
  623.  
  624. > (concatenate 'string '(#\a #\b) '(#\c))
  625. "abc"
  626. > (concatenate 'list "abc" "de")
  627. (#\a #\b #\c #\d #\e)
  628. > (concatenate 'vector '#(3 3 3) '#(3 3 3))
  629. #(3 3 3 3 3 3)
  630.  
  631.  
  632.  
  633. Structures
  634.  
  635. LISP structures are analogous to C structs or Pascal records. Here is
  636. an example:
  637.  
  638. > (defstruct foo
  639.     bar
  640.     baaz
  641.     quux)
  642. FOO
  643.  
  644. This example defines a data type called foo which is a structure
  645. containing 3 fields. It also defines 4 functions which operate on this
  646. data type: make-foo, foo-bar, foo-baaz, and foo-quux. The first one
  647. makes a new object of type foo; the others access the fields of an
  648. object of type foo. Here is how to use these functions:
  649.  
  650. > (make-foo)
  651. #s(FOO :BAR NIL :BAAZ NIL :QUUX NIL) 
  652. > (make-foo :baaz 3)
  653. #s(FOO :BAR NIL :BAAZ 3 :QUUX NIL) 
  654. > (foo-bar *)
  655. NIL
  656. > (foo-baaz **)
  657. 3
  658.  
  659. The make-foo function can take a keyword argument for each of the
  660. fields a structure of type foo can have. The field access functions
  661. each take one argument, a structure of type foo, and return the
  662. appropriate field.
  663.  
  664. See below for how to set the fields of a structure.
  665.  
  666.  
  667.  
  668. Setf
  669.  
  670. Certain forms in LISP naturally define a memory location. For example,
  671. if the value of x is a structure of type foo, then (foo-bar x) defines
  672. the bar field of the value of x. Or, if the value of y is a one-
  673. dimensional array, (aref y 2) defines the third element of y.
  674.  
  675. The setf special form uses its first argument to define a place in
  676. memory, evaluates its second argument, and stores the resulting value
  677. in the resulting memory location. For example,
  678.  
  679. > (setq a (make-array 3))
  680. #(NIL NIL NIL)
  681. > (aref a 1)
  682. NIL
  683. > (setf (aref a 1) 3)
  684. 3
  685. > a
  686. #(NIL 3 NIL)
  687. > (aref a 1)
  688. 3
  689. > (defstruct foo bar)
  690. FOO
  691. > (setq a (make-foo))
  692. #s(FOO :BAR NIL)
  693. > (foo-bar a)
  694. NIL
  695. > (setf (foo-bar a) 3)
  696. 3
  697. > a
  698. #s(FOO :BAR 3)
  699. > (foo-bar a)
  700. 3
  701.  
  702. Setf is the only way to set the fields of a structure or the elements
  703. of an array.
  704.  
  705. Here are some more examples of setf and related functions.
  706.  
  707. > (setf a (make-array 1))    ;setf on a variable is equivalent to setq
  708. #(NIL)
  709. > (push 5 (aref a 1))        ;push can act like setf
  710. (5)
  711. > (pop (aref a 1))        ;so can pop
  712. 5
  713. > (setf (aref a 1) 5)
  714. 5
  715. > (incf (aref a 1))        ;incf reads from a place, increments,
  716. 6                ;and writes back
  717. > (aref a 1)
  718. 6
  719.  
  720.  
  721.  
  722. Booleans and Conditionals
  723.  
  724. LISP uses the self-evaluating symbol nil to mean false. Anything other
  725. than nil means true. Unless we have a reason not to, we usually use the
  726. self-evaluating symbol t to stand for true.
  727.  
  728. LISP provides a standard set of logical functions, for example and, or,
  729. and not. The and and or functions are short-circuiting: and will not
  730. evaluate any arguments to the right of the first one which evaluates to
  731. nil, while or will not evaluate any arguments to the right of the first
  732. one which evaluates to t.
  733.  
  734. LISP also provides several special forms for conditional execution. The
  735. simplest of these is if. The first argument of if determines whether
  736. the second or third argument will be executed:
  737.  
  738. > (if t 5 6)
  739. 5
  740. > (if nil 5 6)
  741. 6
  742. > (if 4 5 6)
  743. 5
  744.  
  745. If you need to put more than one statement in the then or else clause
  746. of an if statement, you can use the progn special form. Progn executes
  747. each statement in its body, then returns the value of the final one.
  748.  
  749. > (setq a 7)
  750. 7
  751. > (setq b 0)
  752. 0
  753. > (setq c 5)
  754. 5
  755. > (if (> a 5)
  756.     (progn
  757.       (setq a (+ b 7))
  758.       (setq b (+ c 8)))
  759.     (setq b 4))
  760. 13
  761.  
  762. An if statement which lacks either a then or an else clause can be
  763. written using the when or unless special form:
  764.  
  765. > (when t 3)
  766. 3
  767. > (when nil 3)
  768. NIL
  769. > (unless t 3)
  770. NIL
  771. > (unless nil 3)
  772. 3
  773.  
  774. When and unless, unlike if, allow any number of statements in their
  775. bodies. (Eg, (when x a b c) is equivalent to (if x (progn a b c)).)
  776.  
  777. > (when t
  778.     (setq a 5)
  779.     (+ a 6))
  780. 11
  781.  
  782. More complicated conditionals can be defined using the cond special
  783. form, which is equivalent to an if ... else if ... fi construction.
  784.  
  785. A cond consists of the symbol cond followed by a number of cond
  786. clauses, each of which is a list. The first element of a cond clause is
  787. the condition; the remaining elements (if any) are the action. The cond
  788. form finds the first clause whose condition evaluates to true (ie,
  789. doesn't evaluate to nil); it then executes the corresponding action and
  790. returns the resulting value. None of the remaining conditions are
  791. evaluated; nor are any actions except the one corresponding to the
  792. selected condition. For example:
  793.  
  794. > (setq a 3)
  795. 3
  796. > (cond
  797.    ((evenp a) a)    ;if a is even return a
  798.    ((> a 7) (/ a 2))    ;else if a is bigger than 7 return a/2
  799.    ((< a 5) (- a 1))    ;else if a is smaller than 5 return a-1
  800.    (t 17))        ;else return 17
  801. 2
  802.  
  803. If the action in the selected cond clause is missing, cond returns what
  804. the condition evaluated to:
  805.  
  806. > (cond ((+ 3 4)))
  807. 7
  808.  
  809. Here's a clever little recursive function which uses cond. You might be
  810. interested in trying to prove that it terminates for all integers x at
  811. least 1. (If you succeed, please publish the result.)
  812.  
  813. > (defun hotpo (x steps)    ;hotpo stands for Half Or Triple Plus One
  814.     (cond
  815.      ((= x 1) steps)
  816.      ((oddp x) (hotpo (+ 1 (* x 3)) (+ 1 steps)))
  817.      (t (hotpo (/ x 2) (+ 1 steps)))))
  818. A
  819. > (hotpo 7 0)
  820. 16
  821.  
  822. The LISP case statement is like a C switch statement:
  823.  
  824. > (setq x 'b)
  825. B
  826. > (case x
  827.    (a 5)
  828.    ((d e) 7)
  829.    ((b f) 3)
  830.    (otherwise 9))
  831. 3
  832.  
  833. The otherwise clause at the end means that if x is not a, b, d, e, or
  834. f, the case statement will return 9.
  835.  
  836.  
  837.  
  838. Iteration
  839.  
  840. The simplest iteration construct in LISP is loop: a loop construct
  841. repeatedly executes its body until it hits a return special form. For
  842. example,
  843.  
  844. > (setq a 4)
  845. 4
  846. > (loop 
  847.    (setq a (+ a 1))
  848.    (when (> a 7) (return a)))
  849. 8
  850. > (loop
  851.    (setq a (- a 1))
  852.    (when (< a 3) (return)))
  853. NIL
  854.  
  855. The next simplest is dolist: dolist binds a variable to the elements of
  856. a list in order and stops when it hits the end of the list.
  857.  
  858. > (dolist (x '(a b c)) (print x))
  859. NIL 
  860.  
  861. Dolist always returns nil. Note that the value of x in the above
  862. example was never nil: the NIL below the C was the value that dolist
  863. returned, printed by the read-eval-print loop.
  864.  
  865. The most complicated iteration primitive is called do. A do statement
  866. looks like this:
  867.  
  868. > (do ((x 1 (+ x 1))
  869.        (y 1 (* y 2)))
  870.       ((> x 5) y)
  871.     (print y)
  872.     (print 'working))
  873. WORKING 
  874. WORKING 
  875. WORKING 
  876. WORKING 
  877. 16 
  878. WORKING 
  879. 32 
  880.  
  881. The first part of a do specifies what variables to bind, what their
  882. initial values are, and how to update them. The second part specifies a
  883. termination condition and a return value. The last part is the body. A
  884. do form binds its variables to their initial values like a let, then
  885. checks the termination condition. As long as the condition is false, it
  886. executes the body repeatedly; when the condition becomes true, it
  887. returns the value of the return-value form.
  888.  
  889. The do* form is to do as let* is to let.
  890.  
  891.  
  892.  
  893. Non-local Exits
  894.  
  895. The return special form mentioned in the section on iteration is an
  896. example of a nonlocal return. Another example is the return-from form,
  897. which returns a value from the surrounding function:
  898.  
  899. > (defun foo (x)
  900.     (return-from foo 3)
  901.     x)
  902. FOO
  903. > (foo 17)
  904. 3
  905.  
  906. Actually, the return-from form can return from any named block -- it's
  907. just that functions are the only blocks which are named by default. You
  908. can create a named block with the block special form:
  909.  
  910. > (block foo
  911.     (return-from foo 7)
  912.     3)
  913. 7
  914.  
  915. The return special form can return from any block named nil. Loops are
  916. by default labelled nil, but you can make your own nil-labelled blocks:
  917.  
  918. > (block nil
  919.     (return 7)
  920.     3)
  921. 7
  922.  
  923. Another form which causes a nonlocal exit is the error form:
  924.  
  925. > (error "This is an error")
  926. Error: This is an error
  927.  
  928. The error form applies format to its arguments, then places you in the
  929. debugger.
  930.  
  931.  
  932.  
  933. Funcall, Apply, and Mapcar
  934.  
  935. Earlier I promised to give some functions which take functions as
  936. arguments. Here they are:
  937.  
  938. > (funcall #'+ 3 4)
  939. 7
  940. > (apply #'+ 3 4 '(3 4))
  941. 14
  942. > (mapcar #'not '(t nil t nil t nil))
  943. (NIL T NIL T NIL T)
  944.  
  945. Funcall calls its first argument on its remaining arguments.
  946.  
  947. Apply is just like funcall, except that its final argument should be a
  948. list; the elements of that list are treated as if they were additional
  949. arguments to a funcall.
  950.  
  951. The first argument to mapcar must be a function of one argument; mapcar
  952. applies this function to each element of a list and collects the
  953. results in another list.
  954.  
  955. Funcall and apply are chiefly useful when their first argument is a
  956. variable. For instance, a search engine could take a heuristic function
  957. as a parameter and use funcall or apply to call that function on a
  958. state description. The sorting functions described later use funcall
  959. to call their comparison functions.
  960.  
  961. Mapcar, along with nameless functions (see below), can replace many
  962. loops.
  963.  
  964.  
  965.  
  966. Lambda
  967.  
  968. If you just want to create a temporary function and don't want to
  969. bother giving it a name, lambda is what you need.
  970.  
  971. > #'(lambda (x) (+ x 3))
  972. (LAMBDA (X) (+ X 3))
  973. > (funcall * 5)
  974. 8
  975.  
  976. The combination of lambda and mapcar can replace many loops. For
  977. example, the following two forms are equivalent:
  978.  
  979. > (do ((x '(1 2 3 4 5) (cdr x))
  980.        (y nil))
  981.       ((null x) (reverse y))
  982.     (push (+ (car x) 2) y))
  983. (3 4 5 6 7)
  984. > (mapcar #'(lambda (x) (+ x 2)) '(1 2 3 4 5))
  985. (3 4 5 6 7)
  986.  
  987.  
  988.  
  989. Sorting and Merging
  990.  
  991. LISP provides two primitives for sorting: sort and stable-sort.
  992.  
  993. > (sort '(2 1 5 4 6) #'<)
  994. (1 2 4 5 6)
  995. > (sort '(2 1 5 4 6) #'>)
  996. (6 5 4 2 1)
  997.  
  998. The first argument to sort is a list; the second is a comparison
  999. function. The sort function does not guarantee stability: if there are
  1000. two elements a and b such that (and (not (< a b)) (not (< b a))), sort
  1001. may arrange them in either order. The stable-sort function is exactly
  1002. like sort, except that it guarantees that two equivalent elements
  1003. appear in the sorted list in the same order that they appeared in the
  1004. original list.
  1005.  
  1006. If you already have two sorted sequences, you can merge them with the
  1007. merge function. Merge is guaranteed to be stable: if an element in the
  1008. first sequence is equivalent to one in the second, the element from the
  1009. first sequence appears first in the output. In the following example,
  1010. char-lessp considers #\a equivalent to #\A.
  1011.  
  1012. > (merge 'string "abc" "ABC" #'char-lessp)
  1013. "aAbBcC"
  1014.  
  1015. Merge, like concatenate, will work with any type of sequence.
  1016.  
  1017. Be careful: sort and merge are allowed to destroy their arguments, so
  1018. if the original sequences are important to you, make a copy with the
  1019. copy-list or copy-seq function.
  1020.  
  1021.  
  1022.  
  1023. Equality
  1024.  
  1025. LISP has many different ideas of equality. Numerical equality is
  1026. denoted by =. Two symbols are eq if and only if they are identical. Two
  1027. copies of the same list are not eq, but they are equal.
  1028.  
  1029. > (eq 'a 'a)
  1030. T
  1031. > (eq 'a 'b)
  1032. NIL
  1033. > (= 3 4)
  1034. T
  1035. > (eq '(a b c) '(a b c))
  1036. NIL
  1037. > (equal '(a b c) '(a b c))
  1038. T
  1039. > (eql 'a 'a)
  1040. T
  1041. > (eql 3 3)
  1042. T
  1043.  
  1044. The eql predicate is equivalent to eq for symbols and to = for numbers.
  1045.  
  1046. The equal predicate is equivalent to eql for symbols and numbers. It is
  1047. true for two conses if and only if their cars are equal and their cdrs
  1048. are equal. It is true for two structures if and only if the structures
  1049. are the same type and their corresponding fields are equal.
  1050.  
  1051.  
  1052.  
  1053. Some Useful List Functions
  1054.  
  1055. These functions all manipulate lists.
  1056.  
  1057. > (append '(1 2 3) '(4 5 6))    ;concatenate lists
  1058. (1 2 3 4 5 6)
  1059. > (reverse '(1 2 3))        ;reverse the elements of a list
  1060. (3 2 1)
  1061. > (member 'a '(b d a c))    ;set membership -- returns the first tail
  1062. (A C)                ;whose car is the desired element
  1063. > (find 'a '(b d a c))        ;another way to do set membership
  1064. A
  1065. > (find '(a b) '((a d) (a d e) (a b d e) ()) :test #'subsetp)
  1066. (A B D E)            ;find is more flexible though
  1067. > (subsetp '(a b) '(a d e))    ;set containment
  1068. NIL
  1069. > (intersection '(a b c) '(b))    ;set intersection
  1070. (B)
  1071. > (union '(a) '(b))        ;set union
  1072. (A B)
  1073. > (set-difference '(a b) '(a))    ;set difference
  1074. (B)
  1075.  
  1076. Subsetp, intersection, union, and set-difference all assume that each
  1077. argument contains no duplicate elements -- (subsetp '(a a) '(a b b)) is
  1078. allowed to fail, for example.
  1079.  
  1080. Find, subsetp, intersection, union, and set-difference can all take a
  1081. :test keyword argument; by default, they all use eql.
  1082.  
  1083.  
  1084.  
  1085. Getting Started
  1086.  
  1087. You can use Emacs to edit LISP code: most Emacses are set up to enter
  1088. LISP mode automatically when they find a file which ends in .lisp, but
  1089. if yours isn't, you can type M-x lisp-mode.
  1090.  
  1091. You can run LISP under Emacs, too: make sure that there is a command in
  1092. your path called "lisp" which runs your favorite LISP. For example, you
  1093. could type
  1094.  
  1095.     ln -s /usr/misc/.allegro/bin/cl ~/bin/lisp
  1096.  
  1097. Then in Emacs type M-x run-lisp. You can send LISP code to the LISP you
  1098. just started, and do all sorts of other cool things; for more
  1099. information, type C-h m from any buffer which is in LISP mode.
  1100.  
  1101. Actually, you don't even need to make a link. Emacs has a variable
  1102. called inferior-lisp-program; so if you add the line
  1103.  
  1104.     (setq inferior-lisp-program "/usr/misc/.allegro/bin/cl")
  1105.  
  1106. to your .emacs file, Emacs will know where to find Allegro LISP when
  1107. you type M-x run-lisp.
  1108.  
  1109. Allegro Common LISP has an online manual for use with Emacs. To use it,
  1110. add the following to your .emacs file:
  1111.  
  1112.     (setq load-path
  1113.           (cons "/afs/cs/misc/allegro/common/omega/emacs" load-path))
  1114.     (autoload 'fi:clman "fi/clman" "Allegro Common LISP online manual." t)
  1115.  
  1116. Then the command M-x fi:clman will prompt you for a LISP topic and
  1117. print the appropriate documentation.
  1118.  
  1119.